﻿# -*- coding: utf-8 -*-
from flask import Blueprint
from model import FollowTable, User
from .common import queryUserCache
from decorator import login_required
from utils import restful
from exts import db
from utils.redis import Redis
from setting import Prefixs

bp = Blueprint('follow', __name__, url_prefix='/follow')


# 尝试关注用户
@bp.route('/<int:up_id>/<isfollow>', methods=['PUT'])
@login_required
def follow_user(up_id, isfollow):
    if isfollow != "true" and isfollow != 'false':
        return restful.fail("url错误！"), 404
    user_info = queryUserCache()
    redis_key = Prefixs.follow_user_set_prefix + str(user_info['id'])
    if isfollow == "true":
        if int(up_id) == int(user_info['id']):
            return restful.fail("不能关注自己！")
        # 代表关注操作
        follow_info = FollowTable(user_id=user_info['id'], follow_user_id=up_id)
        db.session.add(follow_info)
        db.session.commit()
        Redis.sadd(redis_key, up_id)
        return restful.success()
    else:  # 代表取关操作
        follow_info = FollowTable.query.filter_by(user_id=user_info['id'], follow_user_id=up_id).first()
        db.session.delete(follow_info)
        db.session.commit()
        Redis.srem(redis_key, up_id)
        return restful.success()


# 判断用户是否关注
@bp.route('/or/not/<int:up_id>')
@login_required
def is_follow(up_id):
    user_info = queryUserCache()
    follow_info = FollowTable.query.filter_by(user_id=user_info['id'], follow_user_id=up_id).first()
    return restful.success(data=True if follow_info else False)


@bp.route('/common/<int:up_id>')
@login_required
def query_common_follow(up_id):
    user_info = queryUserCache()
    k1 = Prefixs.follow_user_set_prefix + str(user_info['id'])
    k2 = Prefixs.follow_user_set_prefix + str(up_id)
    common_follow = Redis.sinter([k1, k2])
    users = [user.to_dict() for user in User.query.filter(User.id.in_(common_follow)).all()]
    return restful.success(data=users)
